package com.demo.yang.controller;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.demo.yang.bean.Account;
import com.demo.yang.bean.output.LoginOutput;
import com.demo.yang.enums.StatusCode;
import com.demo.yang.service.AccountService;
import com.demo.yang.utils.JSONUtils;
import com.demo.yang.utils.StringUtils;

/**
 * 
 * @author yinbenyang
 * @date 2017年10月31日上午11:32:06
 */
@Controller
@RequestMapping("/login")
public class LoginController extends BaseController{
	private static final Logger LOGGER = LoggerFactory.getLogger(LoginController.class);

	@Autowired
	AccountService accountService;
	
	@RequestMapping
	public String toLogin(){
		return "login";
	}
	
	@ResponseBody
	@RequestMapping(value = "login",method = RequestMethod.POST)
	public String login(@ModelAttribute Account account,HttpServletRequest request){
		LOGGER.info("accountNo:{}，pwd:{}",account.getAccountno(),account.getPwd());
		LoginOutput output = new LoginOutput();
		if(account == null || StringUtils.isEmpty(account.getAccountno()) || StringUtils.isEmpty(account.getPwd())){
			output.setCode(StatusCode.ACCOUNT_OR_PWD_NULL.getIndex()).setMsg(StatusCode.ACCOUNT_OR_PWD_NULL.getMessage());
			return JSONUtils.toJSONString(output);
		}
		//查询用户是否存在
		boolean flag = accountService.isExistAccount(account.getAccountno());
		if(!flag){
			output.setCode(StatusCode.ACCOUNT_NOT_EXIST.getIndex()).setMsg(StatusCode.ACCOUNT_NOT_EXIST.getMessage());
			return JSONUtils.toJSONString(output);
		}
		Account account2 = accountService.login(account.getAccountno(), account.getPwd());
		if(account2 == null){
			output.setCode(StatusCode.ACCOUNT_OR_PWD_ERROR.getIndex()).setMsg(StatusCode.ACCOUNT_OR_PWD_ERROR.getMessage());
			return JSONUtils.toJSONString(output);
		}
		output.setCode(StatusCode.SUCCESS.getIndex()).setMsg(StatusCode.SUCCESS.getMessage());
		output.setData(account2);
		//当验证都通过后，把用户信息放在session里
	    setAccountToSession(request,account2);
		return JSONUtils.toJSONString(output);
	}
}
